library(ggplot2)
library(dplyr)

survey_long <- readRDS("data/df_long.rds")
survey_wide <- readRDS("data/df_wide.rds")
survey_long_csv <- read.csv("data/df_long.csv")


############ Figure 1: Distribution of social distance responses


countries <- sort(unique(survey_long$dem_country_code))
countries_label <- c("Germany", "Spain", "France", "United Kingdom", 
                     "Greece", "Italy", "Netherlands", "Poland", 
                     "Sweden", "United States")

plot_list <- list()

for(x in seq_along(countries)){
  
  i <- countries[x]
  l <- countries_label[x]
  
  plot_data <- survey_long %>% 
    filter(close_relationship != "" & dem_country_code == i & d_ownparty == 0) %>% 
    group_by(close_relationship2) %>% 
    summarise(n = sum(meta_Weight)) %>%
    mutate(freq = n / sum(n))
  
  wmean <- weighted.mean(survey_long$close_num[
    survey_long$close_relationship2 != "" & 
      survey_long$dem_country_code == i &
      !is.na(survey_long$close_num)],
    survey_long$meta_Weight[
      survey_long$close_relationship2 != "" & 
        survey_long$dem_country_code == i &
        !is.na(survey_long$close_num)])
  
  plot <- ggplot(plot_data,
         aes(y = close_relationship2)) +
    geom_bar(aes(x = freq), stat = "identity") +
    ylab("") +
    geom_hline(yintercept= wmean,
               linetype = "dashed") +
    xlim(c(0,0.3)) +
    ggtitle(l) + 
    xlab("Proportion of social distance \n responses") +
    theme_bw() + 
    theme(text= element_text(size = 16))
  
  plot_list[[x]] <- plot
  
}

countries_plot <- grid.arrange(plot_list[[1]], plot_list[[2]], 
                               plot_list[[3]], plot_list[[4]],
                               plot_list[[5]], plot_list[[6]],
                               plot_list[[7]], plot_list[[8]],
                               plot_list[[9]], plot_list[[10]], ncol = 2)

ggsave("figures/Figure1.jpeg", plot = countries_plot,
       height = 12, width = 9, dpi=600)



